package com.gitee.wsl.jvm.okhttp

import android.annotation.SuppressLint
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import java.security.NoSuchProviderException
import java.security.SignatureException
import java.security.cert.CertificateException
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.X509TrustManager

enum class LoginType{
    BASE,DIGEST,BASE_OR_DIGEST
}

fun createInsecureHostnameVerifier(): HostnameVerifier = HostnameVerifier { _, _ -> true }


@SuppressLint("CustomX509TrustManager")
class TrustAllCerts : X509TrustManager {
    @SuppressLint("TrustAllX509TrustManager")
    override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
    }

    @SuppressLint("TrustAllX509TrustManager")
    override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
    }

    override fun getAcceptedIssuers(): Array<X509Certificate> {
        return emptyArray()
    }
}


class X509TrustFileManager(private val mHttpsCertPath: File) : X509TrustManager {
    @SuppressLint("TrustAllX509TrustManager")
    @Throws(CertificateException::class)
    override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}

    @Throws(CertificateException::class)
    override fun checkServerTrusted(
        certs: Array<X509Certificate>,
        authType: String
    ) {
        var `is`: InputStream? = null
        try {
            `is` = FileInputStream(mHttpsCertPath)
            val cf = CertificateFactory.getInstance("X.509")
            val ca = cf.generateCertificate(`is`) as X509Certificate
            for (cert in certs) {
                cert.verify(ca.publicKey)
            }
        } catch (e: FileNotFoundException) {
            throw CertificateException("Untrusted Certificate!", e)
        } catch (e: NoSuchAlgorithmException) {
            throw CertificateException("Untrusted Certificate!", e)
        } catch (e: InvalidKeyException) {
            throw CertificateException("Untrusted Certificate!", e)
        } catch (e: NoSuchProviderException) {
            throw CertificateException("Untrusted Certificate!", e)
        } catch (e: SignatureException) {
            throw CertificateException("Untrusted Certificate!", e)
        } finally {
            try {
                `is`?.close()
            } catch (e: IOException) {
                Timber.tag(TAG).w(e)
            }
        }
    }

    override fun getAcceptedIssuers(): Array<X509Certificate> {
        return emptyArray()
    }

    companion object {
        private const val TAG = "FileTrustManager"
    }
}
